package com.lantosec.hmrp.modules.workflow.listener;

import com.alibaba.fastjson.JSONObject;
import com.lantosec.hmrp.modules.system.service.ISysUserService;
import com.lantosec.hmrp.modules.workflow.enumeration.ProcessVariableEnum;
import com.lantosec.hmrp.modules.workflow.service.IWorkflowRepositoryService;
import com.lantosec.hmrp.modules.workflow.vo.CustomAttributeVO;
import com.lantosec.hmrp.modules.workflow.vo.TaskCountersignVO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 会签任务的条件判断
 *
 * @author lichaowei
 * @date 2020/5/21
 */
@Component
@Log4j2
public class MultiInstanceCompleteTask {

    @Autowired
    private IWorkflowRepositoryService workflowService;
    @Autowired
    private ISysUserService sysUserService;
    /**
     * 评估结果判定条件
     * @param execution 分配的执行实例
     */
    public boolean condition(DelegateExecution execution) {
        log.info("会签条件判断----->processInstanceId:" + execution.getProcessInstanceId());
        // 总实例数
        int nrOfInstances = (int) execution.getVariable("nrOfInstances");
        // 通过的数量
        int agreeCount = (int) execution.getVariable(ProcessVariableEnum.AGREE_COUNT.getCode());
        // 任务操作人用户Id
        String userId = (String) execution.getVariable(ProcessVariableEnum.USER_ID.getCode());

        // 通过比例
        Integer ratio = 0;
        // 一票权用户Id集合
        List<String> oneVoteList = new ArrayList<>();
        TaskCountersignVO countersignVO = getTaskCountersign(execution.getCurrentFlowElement());
        if (!Objects.isNull(countersignVO)) {
            // 会签通过比率
            ratio = countersignVO.getRatio();
            if (countersignVO.getIsOneVote() > 0) {
                // 会签通过比率
                oneVoteList = sysUserService.queryUserIdList(countersignVO.getVoteUser());
            }
        }

        // 一票权判断,一票权的用户可以终结该任务节点，所以始终返回true
        if (CollectionUtils.isNotEmpty(oneVoteList) && oneVoteList.contains(userId)) {
            Integer auditStatus = (Integer) execution.getVariable(ProcessVariableEnum.AUDIT_STATUS.getCode());
            if (!Objects.isNull(auditStatus)) {
                if (auditStatus > 0) {
                    // 一票权用户审核通过，设置通过比例为100%，不通过比例为0%，用于分支流程判断
                    execution.setVariable(ProcessVariableEnum.AGREE_COUNT.getCode(), nrOfInstances);
                    execution.setVariable(ProcessVariableEnum.DISAGREE_COUNT.getCode(), 0);
                } else {
                    execution.setVariable(ProcessVariableEnum.AGREE_COUNT.getCode(), 0);
                    execution.setVariable(ProcessVariableEnum.DISAGREE_COUNT.getCode(), nrOfInstances);
                }
            }
            return true;
        } else {
            // 正常的判断逻辑，计算审核通过比例，然后与配置的通过比例对比
            int result = agreeCount * 100 / nrOfInstances;
            return result >= ratio;
        }
    }

    /**
     * 获取节点的会签配置
     */
    private TaskCountersignVO getTaskCountersign(FlowElement flowElement){
        if (!Objects.isNull(flowElement) && flowElement instanceof UserTask) {
            UserTask userTask = (UserTask) flowElement;
            CustomAttributeVO attributeVO = workflowService.getCustomAttribute(userTask);
            // 节点的会签配置
            return JSONObject.parseObject(attributeVO.getCountersign(), TaskCountersignVO.class);
        }
        return null;
    }

}
